<template>
  <div class="chat-debug">
    <div class="header">
      <h2>SSE 聊天调试</h2>
      <div class="actions">
        <a-button type="primary" @click="checkConnection">检查连接</a-button>
        <a-button @click="clearLogs">清空日志</a-button>
      </div>
    </div>

    <a-card title="连接信息" :bordered="false">
      <a-descriptions bordered>
        <a-descriptions-item label="SSE URL">{{ sseUrl }}</a-descriptions-item>
        <a-descriptions-item label="浏览器支持">
          <a-tag :color="sseSupportColor">{{ sseSupported ? '支持' : '不支持' }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="连接状态">
          <a-tag :color="connectionStatusColor">{{ connectionStatusText }}</a-tag>
        </a-descriptions-item>
      </a-descriptions>
    </a-card>

    <a-card title="检查结果" :bordered="false" v-if="checkResult">
      <a-descriptions bordered>
        <a-descriptions-item label="CORS支持">
          <a-tag :color="checkResult.corsEnabled ? 'green' : 'red'">
            {{ checkResult.corsEnabled ? '支持' : '不支持' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="CORS错误" v-if="checkResult.corsErrorMessage">
          {{ checkResult.corsErrorMessage }}
        </a-descriptions-item>
        <a-descriptions-item label="连接错误" v-if="checkResult.connectionErrorMessage">
          {{ checkResult.connectionErrorMessage }}
        </a-descriptions-item>
      </a-descriptions>
    </a-card>

    <a-card title="测试消息" :bordered="false">
      <a-textarea v-model:value="testMessage" placeholder="输入测试消息" :rows="3" />
      <div class="actions" style="margin-top: 10px;">
        <a-button type="primary" @click="sendTestMessage" :loading="sending">发送测试消息</a-button>
      </div>
    </a-card>

    <a-card title="调试日志" :bordered="false">
      <div class="log-container">
        <div v-for="(log, index) in logs" :key="index" class="log-item" :class="log.type">
          <span class="log-time">{{ formatTime(log.time) }}</span>
          <span class="log-type">[{{ log.type.toUpperCase() }}]</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { message } from 'ant-design-vue';
import { v4 as uuidv4 } from 'uuid';
import { sseClient, SSEConnectionStatus } from '../../api/sseChat';
import { checkSSESupport, checkSSEConnection } from '../../utils/debugHelper';
import type { SSEConnectionCheckResult } from '../../utils/debugHelper';

// 状态
const sseUrl = ref(import.meta.env.VITE_SSE_URL || '/api/sse');
const sseSupported = ref(false);
const connectionStatus = ref<SSEConnectionStatus>(SSEConnectionStatus.CLOSED);
const checkResult = ref<SSEConnectionCheckResult | null>(null);
const logs = ref<Array<{ type: string; time: Date; message: string }>>([]);
const testMessage = ref('');
const sending = ref(false);

// 计算属性
const sseSupportColor = computed(() => sseSupported.value ? 'green' : 'red');
const connectionStatusColor = computed(() => {
  switch (connectionStatus.value) {
    case SSEConnectionStatus.OPEN:
      return 'green';
    case SSEConnectionStatus.CONNECTING:
      return 'blue';
    case SSEConnectionStatus.ERROR:
      return 'red';
    default:
      return 'grey';
  }
});

const connectionStatusText = computed(() => {
  switch (connectionStatus.value) {
    case SSEConnectionStatus.OPEN:
      return '已连接';
    case SSEConnectionStatus.CONNECTING:
      return '连接中';
    case SSEConnectionStatus.ERROR:
      return '连接错误';
    default:
      return '已关闭';
  }
});

// 方法
const addLog = (type: 'info' | 'error' | 'success' | 'warning', message: string) => {
  logs.value.push({
    type,
    time: new Date(),
    message
  });

  // 限制日志数量
  if (logs.value.length > 100) {
    logs.value = logs.value.slice(-100);
  }
};

const formatTime = (date: Date) => {
  return date.toLocaleTimeString() + '.' + date.getMilliseconds().toString().padStart(3, '0');
};

const checkConnection = async () => {
  addLog('info', '检查SSE连接...');
  try {
    checkResult.value = await checkSSEConnection(sseUrl.value);
    
    if (checkResult.value.corsErrorMessage) {
      addLog('warning', `CORS错误: ${checkResult.value.corsErrorMessage}`);
    }
    
    if (checkResult.value.connectionErrorMessage) {
      addLog('error', `连接错误: ${checkResult.value.connectionErrorMessage}`);
    } else {
      addLog('success', '连接检查成功');
    }
  } catch (error) {
    addLog('error', `检查失败: ${error instanceof Error ? error.message : String(error)}`);
  }
};

const clearLogs = () => {
  logs.value = [];
  addLog('info', '日志已清空');
};

const sendTestMessage = () => {
  if (!testMessage.value.trim()) {
    message.warning('请输入测试消息');
    return;
  }

  sending.value = true;
  addLog('info', `发送测试消息: ${testMessage.value}`);
  
  try {
    const sessionId = 'debug-session-' + Date.now();
    const visitorId = 'debug-visitor-' + Date.now();
    
    // 记录请求参数
    addLog('info', `请求参数: sessionId=${sessionId}, visitorId=${visitorId}`);
    
    // 设置回调
    sseClient.setCallbacks({
      onReply: (event) => {
        addLog('success', `收到回复: ${event.content.substring(0, 50)}${event.content.length > 50 ? '...' : ''}`);
        
        if (event.is_final) {
          sending.value = false;
          addLog('info', '收到最终回复，会话结束');
        }
      },
      onReference: (event) => {
        addLog('info', `收到参考: ${event.references.map(ref => ref.name).join(', ')}`);
      },
      onThought: (event) => {
        // 检查是否有思考内容
        if (event.procedures && event.procedures.length > 0) {
          const procedure = event.procedures[0];
          const content = procedure.debugging?.content || '';
          const status = procedure.status || 'unknown';
          
          // 记录思考内容和状态
          addLog(
            status === 'success' ? 'success' : 'info', 
            `思考${status === 'success' ? '完成' : '中'}: ${content.substring(0, 50)}${content.length > 50 ? '...' : ''}`
          );
          
          // 如果是最终思考，更新状态
          if (status === 'success') {
            sending.value = false;
            addLog('info', '思考完成，会话结束');
          }
        } else {
          addLog('info', '收到思考事件，但没有内容');
        }
      },
      onError: (error) => {
        addLog('error', `错误: ${error.message}`);
        sending.value = false;
      },
      onConnectionStatusChange: (status) => {
        connectionStatus.value = status;
        addLog('info', `连接状态变更: ${connectionStatusText.value}`);
        
        if (status === SSEConnectionStatus.CLOSED || status === SSEConnectionStatus.ERROR) {
          sending.value = false;
        }
      }
    });
    
    // 发送消息
    const requestId = sseClient.sendChatMessage(
      testMessage.value,
      sessionId,
      visitorId
    );
    
    addLog('info', `请求已发送，requestId: ${requestId}`);
    
  } catch (error) {
    addLog('error', `发送失败: ${error instanceof Error ? error.message : String(error)}`);
    sending.value = false;
  }
};

// 生命周期
onMounted(() => {
  // 检查SSE支持
  sseSupported.value = checkSSESupport();
  addLog('info', `浏览器SSE支持: ${sseSupported.value ? '是' : '否'}`);
  
  // 获取当前连接状态
  connectionStatus.value = sseClient.getConnectionStatus();
  addLog('info', `当前连接状态: ${connectionStatusText.value}`);
  
  // 监听连接状态变化
  sseClient.setCallbacks({
    onConnectionStatusChange: (status) => {
      connectionStatus.value = status;
    }
  });
  
  // 初始检查
  checkConnection();
});

onUnmounted(() => {
  // 关闭连接
  sseClient.close();
});
</script>

<style scoped>
.chat-debug {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 10px;
}

.log-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #eee;
  padding: 10px;
  background-color: #fafafa;
  border-radius: 4px;
}

.log-item {
  font-family: monospace;
  padding: 4px 0;
  border-bottom: 1px solid #eee;
}

.log-time {
  color: #888;
  margin-right: 10px;
}

.log-type {
  font-weight: bold;
  margin-right: 10px;
}

.log-item.info .log-type {
  color: #1890ff;
}

.log-item.success .log-type {
  color: #52c41a;
}

.log-item.warning .log-type {
  color: #faad14;
}

.log-item.error .log-type {
  color: #f5222d;
}

:deep(.ant-card) {
  margin-bottom: 20px;
}

:deep(.ant-card-head) {
  min-height: auto;
}
</style> 